﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text.RegularExpressions;
using System.Web.Caching;
using System.Web.Script.Serialization;

namespace mBlog.Core
{

    public interface ITwitterService
    {
        IList<string> GetTweets();
    }

    public class TwitterService : ITwitterService
    {
        private const string TWITTER_USER = "jun1st";
        private const string TWITTER_APIURL =
            @"http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";

        private object locker = new object();

        public IList<string> GetTweets()
        {

            if (HttpRuntime.Cache.Get(TWITTER_USER) == null)
            {
                lock(locker)
                {
                    if(HttpRuntime.Cache.Get(TWITTER_USER) == null)
                    {
                        HttpRuntime.Cache.Add(TWITTER_USER,
                            LoadTweets(),
                            null,
                            DateTime.Now.AddMinutes(10),
                            Cache.NoSlidingExpiration,
                            CacheItemPriority.Default,
                            null);

                    }
                }
            }

            return (List<string>)HttpRuntime.Cache.Get(TWITTER_USER);
        }

        private IList<string> LoadTweets()
        {
            var ls = new List<string>();

            var jss = new JavaScriptSerializer();
            var d = jss.Deserialize<List<Dictionary<string, object>>>(
                new WebClient().DownloadString(TWITTER_APIURL + "jun1st")
                );

            foreach (var x in d)
                ls.Add(Linker((string)x["text"]));

            return ls;
        }

        private string Linker(string tweet)
        {
            string s = Regex.Replace(
                            tweet,
                            @"[a-z]+://[^\s]+",
                            x => "<a href='" + x.Value.Replace("'", "&quot;") + "'>" + x.Value + "</a>",
                            RegexOptions.Compiled | RegexOptions.IgnoreCase
                            );

            return s;
        }


    }
}